package com.haohan.cloud.scm.bill.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.haohan.cloud.scm.api.bill.entity.SettlementAccount;
import com.haohan.cloud.scm.api.constant.NumberPrefixConstant;
import com.haohan.cloud.scm.api.constant.enums.bill.SettlementStyleEnum;
import com.haohan.cloud.scm.bill.mapper.SettlementAccountMapper;
import com.haohan.cloud.scm.bill.service.SettlementAccountService;
import com.haohan.cloud.scm.common.tools.util.ScmIncrementUtil;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author dy
 * @date 2019/11/27
 */
@Service
@AllArgsConstructor
public class SettlementAccountServiceImpl extends ServiceImpl<SettlementAccountMapper, SettlementAccount> implements SettlementAccountService {
    private final ScmIncrementUtil scmIncrementUtil;

    @Override
    public boolean save(SettlementAccount entity) {
        if (StrUtil.isEmpty(entity.getSettlementSn())) {
            String sn = scmIncrementUtil.inrcSnByClass(SettlementAccount.class, NumberPrefixConstant.SETTLEMENT_ACCOUNT_SN_PRE);
            entity.setSettlementSn(sn);
        }
        return retBool(baseMapper.insert(entity));
    }

    @Override
    public SettlementAccount fetchBySn(String settlementSn) {
        return baseMapper.selectList(Wrappers.<SettlementAccount>query().lambda()
                .eq(SettlementAccount::getSettlementSn, settlementSn)).stream().findFirst().orElse(null);
    }

    @Override
    public SettlementAccount fetchByBillSn(String billSn) {
        return baseMapper.selectList(Wrappers.<SettlementAccount>query().lambda()
                .eq(SettlementAccount::getBillSn, billSn)).stream().findFirst().orElse(null);
    }

    /**
     * 根据汇总结算单号 查询所有明细
     *
     * @param settlementSn
     * @return
     */
    @Override
    public List<SettlementAccount> fetchDetailOfSummarySn(String settlementSn) {
        return baseMapper.selectList(Wrappers.<SettlementAccount>query().lambda()
                .eq(SettlementAccount::getSettlementStyle, SettlementStyleEnum.detail)
                .eq(SettlementAccount::getSummarySettlementSn, settlementSn)
        );
    }

    @Override
    public List<SettlementAccount> findListByOrderSn(String orderSn) {
        return baseMapper.selectList(Wrappers.<SettlementAccount>query().lambda()
                .eq(SettlementAccount::getOrderSn, orderSn)
        );
    }
}
